package com.tansun.easycare.modules.rule.web.jfast;


import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.springframework.util.StringUtils;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.HandlerMapping;

public abstract class BaseMethodArgumentResolver
        implements HandlerMethodArgumentResolver {
    protected Map<String, String[]> getPrefixParameterMap(String namePrefix, NativeWebRequest request, boolean subPrefix) {
        Map<String, String[]> result = new HashMap<String, String[]>();

        Map<String, String> variables = getUriTemplateVariables(request);

        int namePrefixLength = namePrefix.length();
        for (String name : variables.keySet()) {
            if ((!StringUtils.isEmpty(namePrefix)) && (name.startsWith(namePrefix))) {
                if (subPrefix) {
                    if (name.length() > namePrefix.length()) {
                        char ch = name.charAt(namePrefix.length());
                        if (!illegalChar(ch)) {
                            result.put(name.substring(namePrefixLength + 1), new String[]{(String) variables.get(name)});
                        }
                    }
                } else {
                    result.put(name, new String[]{(String) variables.get(name)});
                }
            } else {
                result.put(name, new String[]{(String) variables.get(name)});
            }
        }
        Iterator<String> parameterNames = request.getParameterNames();
        while (parameterNames.hasNext()) {
            String name = (String) parameterNames.next();
            if ((!StringUtils.isEmpty(namePrefix)) && (name.startsWith(namePrefix))) {
                if (subPrefix) {
                    if (name.length() > namePrefix.length()) {
                        char ch = name.charAt(namePrefix.length());
                        if (!illegalChar(ch)) {
                            result.put(name.substring(namePrefixLength + 1), request.getParameterValues(name));
                        }
                    }
                } else {
                    result.put(name, request.getParameterValues(name));
                }
            } else {
                result.put(name, request.getParameterValues(name));
            }
        }
        return result;
    }

    private boolean illegalChar(char ch) {
        return (ch != '.') && (ch != '_') && ((ch < '0') || (ch > '9'));
    }

    protected final Map<String, String> getUriTemplateVariables(NativeWebRequest request) {
        Map<String, String> variables =
                (Map) request.getAttribute(
                        HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE, 0);
        return (Map<String, String>) (variables != null ? variables : Collections.emptyMap());
    }
}
